package com.atguigu.petstore.sys.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.petstore.common.execption.PetstoreException;
import com.atguigu.petstore.common.result.ResultCodeEnum;
import com.atguigu.petstore.common.util.MD5;
import com.atguigu.petstore.sys.entity.SysUser;
import com.atguigu.petstore.sys.service.SysLoginService;
import com.atguigu.petstore.sys.service.SysUserService;
import com.atguigu.petstore.sys.vo.SysLoginResp;
import com.atguigu.petstore.sys.vo.SysLoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

public class SysLoginServiceImpl implements SysLoginService {
    @Autowired
    SysUserService sysUserService;

    @Autowired
    StringRedisTemplate redisTemplate;
    @Override
    public String login(SysLoginVo sysLoginVo) {
        Boolean captcha = checkCaptcha(sysLoginVo.getDeviceId(), sysLoginVo.getCode());//检查设备id和验证码
        if (!captcha){
            throw new PetstoreException(ResultCodeEnum.USER_CAPTCHA_INVAILD);
        }
        String encrypt = MD5.encrypt(sysLoginVo.getPassword());
        SysUser user = sysUserService.lambdaQuery()
                .eq(SysUser::getLoginName, sysLoginVo.getAccount())
                .eq(SysUser::getLoginPwd, encrypt)  //后端的密码用了MD5加密 前端传来的数据也要加密
                .one();//查询这一个用户的意思

        if (user==null){
            throw new PetstoreException(ResultCodeEnum.USER_ACCOUNT_PWD_ERROR);
        }
        //如果用户存在 则需要创造token给前端 和redis保存
        //UUID 唯一的
        String token = UUID.randomUUID().toString().replace("-", "");
        //redis 存数据 是K V结构 V写为 登录用户的JSON串   这是登录凭据 redis中存储一份是为了其他客服端验证
        String key = "user:login"+token;
        redisTemplate.opsForValue().set(key, JSON.toJSONString(user),7, TimeUnit.DAYS);
        return token;
    }

    @Override
    public Boolean checkCaptcha(String deviceId,String captcha) {
        //所有前端都有唯一的设备id 因为多数人访问的时候 验证码可能一样 但是设备id不一样
                //前缀"user:login" 可以提取出来其实
            String key = "user:login" + deviceId+ ":" + captcha.toLowerCase();
        return redisTemplate.delete(key);
    }
}
